package com.daodao.daodaoschedule.infrastructure.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author mal
 * @date 2022-09-02 17:26
 */
public class StringUtil {

    private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);

    private static final String FIELD_START = "\\$\\{";
    private static final String FIELD_END = "}";

    private static final String REGEX = FIELD_START + "([^}]+)" + FIELD_END;
    private static final Pattern PATTERN = Pattern.compile(REGEX);

    /**
     * 格式化字符串
     *
     * @param template
     * @param objects
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static String formatTemplate(String template, Map<String, Object> objects) {
        Matcher m = PATTERN.matcher(template);
        String result = template;

        try {
            while (m.find()) {
                String[] found = m.group(1).split("\\.");

                Object o = objects.get(found[0].trim());
                String newVal;
                if (found.length > 1) {
                    Field f = o.getClass().getField(found[1].trim());
                    newVal = f.get(o).toString();
                } else {
                    newVal = o == null ? "null" : o.toString();
                }
                result = result.replaceFirst(REGEX, newVal);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error("", e);
        }
        return result;
    }
}
